/*
 * @Author: enmotion 
 * @Date: 2023-12-01 15:22:04 
 * @Last Modified by: enmotion
 * @Last Modified time: 2023-12-01 17:48:45
 * 消息中心处理模块，主要针对 主子应用通讯情况;
 */

import { useRouter } from "@src/router/use.lib";
import type { RouteLocationRaw } from "vue-router";
import microApp from "@micro-zoe/micro-app";

/**
 * 消息类型定义命名空间
 */

/**
 * 路由跳转操作类型
 */


export declare namespace MicroAppEvent  {
  export type AppEvnet = RouterEvent; //子应用事件
  export type RouterPayload = {
    method: 'push'|'replace',
    data:RouteLocationRaw
  }|{
    method: 'go',
    data:number,
  }|{
    method: 'back',
    data?:number
  };
  export type RouterEvent = { // 路由事件
    type:'router',
    payload:RouterPayload
  };
  export type SubmitEvent = { // 提交事件
    type:'submit',
    payload:Record<string,any>,
  };
};
// 接受方法；
export const eventBusOnMessageHandler = (event:MicroAppEvent.AppEvnet, proxyInstance:any)=>{
  const subHandlerMapping:{
    'router':(payload:MicroAppEvent.RouterPayload,proxyInstance:any)=>void
    // 'submit':(payload:Record<string,any>,proxyInstance:any)=>void
  } = {
    'router':routerEventHandler,
    // 'submit':submitEventHandler
  };
  subHandlerMapping[event.type](event.payload as any,proxyInstance);
};

export const eventBusHostSendMessageToSub = (name:string,event:MicroAppEvent.AppEvnet)=>{
  microApp.setData(name,event);
};

export const eventBusDispatch = (event:MicroAppEvent.AppEvnet)=>{
  window.microApp.dispatch(event);
};

function routerEventHandler(payload:MicroAppEvent.RouterPayload){
  const router = useRouter();
  // console.log(router,payload);
  router && router[payload?.method](payload?.data as any);
};

// function submitEventHandler(payload:Record<string,any>,proxyInstance:any){
//   // submit code gose here .....
// }